﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordNet.Core.ElementContracts;
using WordNet.Core.Extensions;

namespace WordNet.Core
{
    public class SynsetID:ISynsetID
    {

        public const String synsetIDPrefix = "SID-";

        private readonly int _offset;
        private readonly POS _pos;

        public SynsetID(int offset, POS pos)
        {
            if (pos == null)
                throw new ArgumentNullException();
            offset.CheckOffset();

            _offset = offset;
            _pos = pos;
        }
        public int Offset
        {
            get { return _offset; }
        }

        public POS PartOfSpeech
        {
            get { return _pos; }
        }

        public override int GetHashCode()
        {
            const int PRIME = 31;
            int result = 1;
            result = PRIME * result + _offset;
            result = PRIME * result + _pos.GetHashCode();
            return result;
        }

        public override bool Equals(Object obj)
        {
            if (Object.ReferenceEquals(obj, null))
                return false;
            if (Object.ReferenceEquals(this, obj))
                return true;
            ISynsetID other = obj as ISynsetID;
            if(other == null)
                return false;
            
            if (_offset != other.Offset)
                return false;
            if (!_pos.Equals(other.PartOfSpeech))
                return false;
            return true;
        }

        public override String ToString()
        {
            StringBuilder sb = new StringBuilder(14);
            sb.Append(synsetIDPrefix);
            sb.Append(_offset.ZeroFillOffset());
            sb.Append('-');
            sb.Append(Char.ToUpper(_pos.Tag));
            return sb.ToString();
        }

        public static SynsetID parseSynsetID(String value)
        {
            if (value == null)
                throw new ArgumentNullException();

            value = value.Trim();
            if (value.Length != 14)
                throw new ArgumentException();

            if (!value.StartsWith("SID-"))
                throw new ArgumentException();

            // get offset
            int offset = int.Parse(value.Substring(4, 12));

            // get pos
            char tag = Char.ToLower(value[13]);
            POS pos = POS.GetPartOfSpeech(tag);
            if (pos == null)
                throw new ArgumentException("unknown part of speech tag: " + tag);

            return new SynsetID(offset, pos);
        }
    }
}
